var express = require('express');
var router = express.Router();
var mysqli = require('../utils/dbconfig')

class BaseController {

    static initRouter() {
        let result = {
            code: 0,
            msg: "",
            data: [],
        }
        router.post('/postInfo', function (req, res) {
            result["code"] = 0;
            result["msg"] = "post请求";
            res.json(result);
        })
        router.get('/getInfo', function (req, res) {
            result["code"] = 0;
            result["msg"] = "get请求";
            res.json(result);
        })
        router.get('/getuser', function (req, res) {
            mysqli.select('SELECT * FROM `users`', function (err, sqldata) {
                if (err) {
                    result.code = 1;
                    result.msg = "失败";
                }
                result.code = 0;
                result.msg = "获取用户信息";
                result.data = sqldata
                res.json(result);
            })
        })

        router.post('/addUser', function (req, res) {
            mysqli.insertData('INSERT INTO users set ? ', req.body, function (err) {
                if (err) {
                    result.code = 1;
                    result.msg = "失败";
                }
                result.code = 0;
                result.msg = "插入用户信息成功";
                result.data = req.body
                res.json(result);
            })
        })

        router.get('/getById', function (req, res) {
            mysqli.selectById(`select * from users where id=${req.query.id}`, function (err, sqldata) {
                if (err) {
                    result.code = 1;
                    result.msg = "失败";
                }
                result.code = 0;
                result.msg = "获取用户信息成功";
                result.data = sqldata
                res.json(result);
            })
        })
        router.post('/updateUser', function (req, res) {
            mysqli.updateData(`UPDATE users set ? where id=${req.query.id}`, req.body, function (err) {
                if (err) {
                    result.code = 1;
                    result.msg = "失败";
                }
                result.code = 0;
                result.msg = "更新用户信息成功";
                result.data = req.body
                res.json(result);
            })
        })

        router.get('/delById', function (req, res) {
            mysqli.deleteById(`delete from users where id=${req.query.id}`, function (err) {
                if (err) {
                    result.code = 1;
                    result.msg = "失败";
                }
                result.code = 0;
                result.msg = "删除用户信息成功";
                res.json(result);
            })
        })



        return router;
    }
}
module.exports = BaseController.initRouter()